package com.gmq.controller;

import com.gmq.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;

    @PostMapping("/upload")
    public R<String> upload(@RequestBody MultipartFile file) {
        String s = UUID.randomUUID().toString();
        String filename = file.getOriginalFilename();
        //获取后缀
        String s1 = filename.substring(filename.lastIndexOf("."));
        //转存图片
        try {
            file.transferTo(new File(basePath + s + s1));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.success(s + s1);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        //下载指定的图片
        //当前端请求图片资源的时候就会访问到这里
        try {
            //使用输入流读取图片
            InputStream inputStream = new FileInputStream(new File(basePath + name));
            //获取一个输出流
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
